package com.glela.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.platform.mapper.VisitorClickRecordMapper;
import com.glela.platform.model.VisitorClickRecord;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

public class RedisTask {

	private static final Logger logger = LoggerFactory.getLogger(RedisTask.class);

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private VisitorClickRecordMapper visitorClickRecordMapper;

	public void batchSaveDataToDB() {
		Jedis jedis = null;
		try {
			jedis = redisUtil.getJedis();
			Pipeline pipeline = jedis.pipelined();
			Set<String> setStr = redisUtil.smembers(RedisKeys.VISTOR_RECORED);
			List<VisitorClickRecord> recordList = new ArrayList<VisitorClickRecord>();
			if (setStr != null && setStr.size() > 0) {
				for (String json : setStr) {
					if (!StringUtils.isEmpty(json)) {
						VisitorClickRecord record = JSONObject.parseObject(json, VisitorClickRecord.class);
						if (record != null) {
							recordList.add(record);
						}
					}
				}
				if (recordList != null && recordList.size() > 0) {
					visitorClickRecordMapper.batchInsertVisitRecord(recordList);
					redisUtil.flushDB();
				}
			}
			pipeline.sync();
		} catch (Exception e) {
			logger.error("batchSaveDataToDB异常:", e);
		} finally {
			if (jedis != null) {
				redisUtil.returnJedis(jedis);
			}
		}
	}
}
